#include "ElementEnemy.h"

ElementEnemy::ElementEnemy(vector3<int> pos)
    :deltaPos(0,0,0),detectArea(vector3<float>(),vector3<float>())
{
    type=ENEMY;
    speed=5;
    detectWidth=20;
    detectDepth=20;
    activated=true;
    isCollidable=true;
    isDynamic=true;
    geometry = AABB(vector3<float>(0,0,0),vector3<float>(1,2,1));
    translate(pos.cast<float>());
    recalcDetectArea();
    oldPos=s.position;
}

void ElementEnemy::invokeCollisionEvent(Character* c){
    c->damage(10);
}

void ElementEnemy::invokeActivateEvent(){

}

void ElementEnemy::setDetectionDepth(int _depth) {
    if (_depth < 0) {
        return;
    }
    detectDepth = _depth;
    recalcDetectArea();
}

void ElementEnemy::setDetectionWidth(int _width) {
    if (_width < 0) {
        return;
    }
    detectWidth = _width;
    recalcDetectArea();
}

void ElementEnemy::invokeUpdateEvent(Character *c){
    recalcDetectArea();
    if(detectArea.hasContactedAABB(c->geometry)){
        vector3<float> spd = (c->s.position-s.position);
        spd.y=0;
        s.velocity = spd.unit()*speed;
    }else
    {
        s.velocity.x=0;
        s.velocity.z=0;
    }

}

void ElementEnemy::activate(){

}

void ElementEnemy::deactivate(){

}

void ElementEnemy::render(){
    static GLuint dlID=0;
    glPushMatrix();
    glTranslatef(s.position.x,s.position.y,s.position.z);

    if(!dlID){
        dlID=glGenLists(1);
        glNewList(dlID,GL_COMPILE_AND_EXECUTE);
        glColor3f(0,0,1);
        Drawing::drawCuboid(vector3<float>(0,0,0),vector3<float>(1,2,1));
        glEndList();
    }else glCallList(dlID);

    glPopMatrix();
}

void ElementEnemy::resetPostion()
{
    setPosition(oldPos);
    s.velocity=vector3<float>(0,0,0);
    recalcDetectArea();
}

void ElementEnemy::editorModeRender()
{
    render();
    glPushMatrix();
    Drawing::drawWireCuboid(detectArea.start.cast<int>(),detectArea.end.cast<int>());
    glPopMatrix();
}

